package com.xmall.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.listener.impl.PropertiesListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

@Slf4j
@Component
public class NacosConfigListener implements ApplicationListener<ApplicationReadyEvent> {

    @Resource
    NacosConfigManager nacosConfigManager;

    @Value("${spring.application.name}")
    private String dataId;

    @Value("${spring.cloud.nacos.config.file-extension}")
    private String fileExtension;

    @Value("${spring.cloud.nacos.config.group}")
    private String group;

    private List<IConfigChangeHandler> handlerList;

    @Autowired(required = false)
    public void setHandlerList(List<IConfigChangeHandler> handlerList) {
        this.handlerList = handlerList;
    }


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        try {
            nacosConfigManager.getConfigService().addListener(dataId + "." + fileExtension, group, new PropertiesListener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                @Override
                public void innerReceive(Properties properties) {
                    if(CollectionUtil.isNotEmpty(handlerList)) {
                        handlerList.forEach(handler -> handler.handle(properties));
                    }
                }
            });
        } catch (NacosException e) {
            log.info("NacosConfigListener error：{}", e.getMessage());
        }
    }
}
